/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jardinevolutivo;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import org.jgap.Chromosome;
import org.jgap.Configuration;
import org.jgap.FitnessFunction;
import org.jgap.Gene;
import org.jgap.Genotype;
import org.jgap.IChromosome;
import org.jgap.impl.DefaultConfiguration;
import org.jgap.impl.IntegerGene;

/**
 *
 * @author Luis Roberto
 */
public class Jardin extends Canvas{
    
    private Flor[] flores;
    private Configuration conf;
    private FitnessFunction adaptacion;
    private Genotype poblacion;
    private final int N = 10;
    private final int ANCHO = 1000;
    private final int ALTO = 500;
    
    public Jardin() throws Exception{
        setSize(ANCHO, ALTO);
        setBackground(Color.CYAN);
        conf = new DefaultConfiguration();
        adaptacion = new Adaptacion();
        conf.setFitnessFunction(adaptacion);
        Gene[] genes = new Gene[3];
        genes[Flor.TAM_FLOR] = new IntegerGene(conf, 10, 70);
        genes[Flor.TAM_TALLO] = new IntegerGene(conf, 100, 300);
        genes[Flor.COLOR_FLOR] = new IntegerGene(conf, 0, 2);
        
        Chromosome cromosoma = new Chromosome(conf, genes);
        conf.setSampleChromosome(cromosoma);
        conf.setPopulationSize(N);
        
        poblacion = Genotype.randomInitialGenotype(conf);
        
        IChromosome[] isujetos = poblacion.getChromosomes();
        
        flores = new Flor[N];
        //POBLACION INICIAL
        for (int i = 0; i < N; i++) {
            int[] aux = new int[3];
            Gene[] auxg = isujetos[i].getGenes();
            for (int j = 0; j < 3; j++) {
                aux[j] = (Integer) auxg[j].getAllele();
            }
            
            flores[i] = new Flor( (ANCHO/N/2) + (ANCHO/N)*i, Math.round((float)0.95*getHeight()), aux );
            
        } 
    }
    
    @Override
    public void paint(Graphics g){
        //Dibujar el suelo
        g.setColor(Color.gray);
        g.fillRect(0, Math.round((float)0.95*getHeight()) , getWidth(), Math.round((float)0.05*getHeight()) );
        
        for (Flor flor : flores) {
            flor.dibujar(g);
        }
    }
    
    public void evolucionar(){
            poblacion.evolve();
        
            IChromosome[] isujetos = poblacion.getChromosomes();

            for (int i = 0; i < N; i++) {
                int[] aux = new int[3];
                Gene[] auxg = isujetos[i].getGenes();
                for (int j = 0; j < 3; j++) {
                    aux[j] = (Integer) auxg[j].getAllele();
                }

                flores[i].cambiarGenes(aux);
            }
            repaint();
            
        
    }
}
